#ifndef RESOURCE_STREAM_H_INCLUDED__
#define RESOURCE_STREAM_H_INCLUDED__

#include <streambuf>
#include <iostream>
#include <vector>

class CResource
{
public:
	void WriteByte(char c)
	{
		ss_.write(&c, sizeof(char));
	}
	char ReadByte()
	{
		char c;
		ss_ >> c;
		return c;
	}
	std::string Content() const
	{
		return ss_.str();
	}

private:
	std::stringstream ss_;
};

template <class charT, class traits = std::char_traits<charT>>
class basic_resource_stream_buf : public std::basic_streambuf<charT, traits>
{
    typedef typename traits::int_type int_type;
    typedef typename traits::pos_type pos_type;
    typedef typename traits::off_type off_type;

public:
	~basic_resource_stream_buf() { sync(); }
	basic_resource_stream_buf(CResource& res) : res_(res) {}

private:
	basic_resource_stream_buf(const basic_resource_stream_buf&);
	basic_resource_stream_buf& operator= (const basic_resource_stream_buf&);

    int_type overflow(int_type c)
	{
		res_.WriteByte(c);
        return traits::not_eof(c);
    }

	int_type underflow()
	{
		int_type c = res_.ReadByte();

		// If nothing was read, then the end is here.
		if (c == 0)
			return traits::eof();
 
		return c;
	}
	
	CResource& res_;
};

typedef basic_resource_stream_buf<char> CResourceStreamBuf;
typedef basic_resource_stream_buf<wchar_t> CResourceStreamBufW;

#endif
